import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import {SettingsService, TitleService} from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { wfglService } from '../../../../service/wfgl/wfgl.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import {insService} from "../../../../service/ins/ins.service";
import {ProductService} from "../../../../service/prod/product.service";

@Component({
  selector: 'wfgl-view-edit',
  templateUrl: './wfgl-edit.component.html',
  styleUrls: ['./wfgl-edit.component.less']
})
export class wfglViewEditComponent implements OnInit, OnDestroy {
  product:  any = {
    id:null,
    orderNo: null,
    cusName: null,
    cusMobile: null,
    orderCartype: null,
    orderCarno: null,
    gpsStatus: null /*No show*/,
    orderPeriod: null,
    orderAmount: null
  };
  wfData: any = {
    fxjOut11: null, // 外访人姓名
    fxjOut12: null, // 外访人电话
    fxjOut13: null, // 外访地址
    fxjOut14: null, // 外访内容
    fxjOut15: null // 外访日期
  }

  q: any = {
    bpmStatus:"",
    // fiName: '',
    // cusMobile: '',
    // cusIncard: '',
    orderNo: '',
    fxjOut16: ''
  };
  checkedList = [];
  // pageSize
  ps = 10;
  url = this.wfglService.dhlist();

  columns: SimpleTableColumn[] = [
    { title: '订单编号', index: 'fxjOut16' },
    { title: '客户姓名', index: 'fxjOut17' },
    { title: '联系电话', index: 'fxjOut18' },
    { title: '车型', index: 'fxjOut19' },
    { title: '车牌', index: 'fxjOut20' },
    { title: 'GPS状态', index: 'fxjOut21' },
    { title: '贷款期数', index: 'fxjOut22' },
    { title: '融资金额', index: 'fxjOut23' },
    { title: '外访人姓名', index: 'fxjOut11' },
    { title: '外访人电话', index: 'fxjOut12' },
    { title: '外访地址', index: 'fxjOut13' },
    { title: '外访内容', index: 'fxjOut14' },
    { title: '外访日期', index: 'fxjOut15' },
  ];
  bpmStatus =  [{text: '未抵押', value: '1'}, {text: '已抵押', value: '10'}];

  MAX_COUNT = 60;
  tabIndex = 0;
  saleing = false;
  private sub: any;

  // 预览图片对象
  previewImage = '';
  // 是否可以预览
  previewVisible = false;

  uploadUrl = '';
  avatarParam = { sbtype: 'No',  filetype:'ma',orderNo: 'no'};
  fileList = [ ];
  avatarUrl:string;
  loading = false;


  constructor(
    private productService: ProductService,

    public setting: SettingsService,
    private msg: NzMessageService,
    private modalService: NzModalService,
    private wfglService: wfglService,
    private emit: EmitterService,
    private notification: NzNotificationService,
    private route: ActivatedRoute,
    private titleService: TitleService,
    private cnt: Constant,
    private router: Router,
    private comm: CommService
  ) {}

  ngOnInit(): void {

    // this.loadbpmStatus();

    this.uploadUrl = this.productService.uploadUrl();

    // 获取参数
    this.sub = this.route.params.subscribe(params => {
      this.product.id = params["id"]
      console.log("this.product.id****************"+this.product.id);
      // 获取商品详情
      this.getProductInfo();
      // this.getfileList(this.product.id);

    });
    // 隐藏reusetab
    setTimeout(() => {
      this.emit.sendMessage("HIDE_REUSE_TAB");
    }, 1000);
  }
  loadbpmStatus() {
    this.bpmStatus = [];
    this.comm.getType("bpm_status").subscribe(data => {
      const ret: ServiceResult = <ServiceResult> data;
      if (ret.ok ) {
        for (const row of ret['data']) {
          this.bpmStatus.push({ text: row.typename, value: row.typecode });
        }
      }
    })
  }
  // 显示reusetab
  ngOnDestroy() {
    this.emit.sendMessage("SHOW_REUSE_TAB");
  }

  changeTab(index) {
    // 使用异步的方式更新组件, 防止ngIf错误
    Promise.resolve(null).then(() => this.tabIndex = index);
  }



  getProductInfo() {
    this.wfglService.getProduct(this.product.id).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      this.product = data.data;
      console.log(this.product);
      this.avatarParam = { sbtype: 'No',  filetype:'wf',orderNo: this.product.orderNo};
      this.titleService.setTitle("编辑产品");

      // this.getfileList(this.product.orderNo);

      this.q.fxjOut16 = this.product.orderNo;

      if (data.data.fxjOrderAttaList.length > 0) {
        let flag = 0;
        for (const detail of data.data.fxjOrderAttaList) {
          if(detail.attaType == 'wf'){
            this.fileList.push( {
              uid: flag,
              name: detail.attaName,
              status: 'done',
              url: detail.attaUrl,
              id: detail.id
            } )
            flag++;
          }
        }
      };

    })
  }
  getfileList(id) {
    this.productService.getfileList(id,"wf").pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      console.log("wfgl*****************"+JSON.stringify(data));
      if (data.data.length > 0) {
        let flag = 0;
        for (const detail of data.data) {
          this.fileList.push( {
            uid: flag,
            name: detail.attaName,
            status: 'done',
            url: detail.attaUrl,
            id: detail.id
          } )
          flag++;
        }
      };
      console.log(this.fileList);
    })
  }




  back() {
    this.router.navigate(['/wfgl/wfgl']);
  }

  checkboxChange(list: any[]) {
    this.checkedList = list;
  }


  save() {

    let dhjLoanins = {
      updateBy: this.setting.user.username,
      id: this.product.id,
      fxjOut11: this.wfData.fxjOut11,
      fxjOut12: this.wfData.fxjOut12,
      fxjOut13: this.wfData.fxjOut13,
      fxjOut14: this.wfData.fxjOut14,
      fxjOut15: this.wfData.fxjOut15,
      fxjOut16: this.product.orderNo,
      fxjOut17: this.product.cusName,
      fxjOut18: this.product.cusMobile,
      fxjOut19: this.product.orderCartype,
      fxjOut20: this.product.orderCarno,
      fxjOut21: this.product.gpsStatus,
      fxjOut22: this.product.orderPeriod,
      fxjOut23: this.product.orderAmount
    };

    // 调用接口
    this.wfglService.editPro(dhjLoanins).pipe(
      catchError(err => {
        return of(err);
      })
    ).subscribe(data => {
      if (data.ok === true) {
        this.msg.success('修改成功');
        this.emit.sendMessage("RELOAD_GOODS_LIST");
        setTimeout(() => {
          this.back();
        }, 1000);
      } else {
        this.msg.error(data['message']);
      }
    })
  }

  changeColor(res) {
    this.product.colorSort = res.color.hex;
  }

  beforeUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.msg.warning(`不支持的格式: ${file.type}`);
    }
    const isLt2M = file.size / 1024 / 1024 < 10;
    if (!isLt2M) {
      this.msg.warning('图片不能超过2MB!');
    }
    return (isJPG || isPNG) && isLt2M;
  }

  private getBase64(img: File, callback: (img: any) => void) {
    if (img) {
      const reader = new FileReader();
      reader.addEventListener('load', () => callback(reader.result));
      reader.readAsDataURL(img);
    }
  }

  handleChange(info: { file: UploadFile }) {
    if (info.file.status === 'uploading') {
      this.loading = true;
      return;
    }
    if (info.file.status === 'done') {
      this.getBase64(info.file.originFileObj, (img: any) => {
        this.loading = false;
        this.avatarUrl = img;
      });
    }
    if (info.file.status === 'error') {
      this.msg.error(info.file.error.error);
    }
  }

  handlePreview = (file: UploadFile) => {
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }


    // 图片 wuwq
    upLoadChange(event) {
      console.log(event);
      let file = event ? event.file : null;
      console.log(file);
      let datas = file && file.id ? file : file.response;
      console.log(datas);
      if (datas) {
          if (event.type == 'success') {
              console.log('ss');
          } else if (event.type == 'removed') {
            console.log('aa');
            let picId = file.id ? file.id : file.response[0].fileId
            this.delPic(picId);
          }
      }
    }
  
  
    // 删除图片 wuwq
    delPic(id) {
      this.wfglService.delfile(id).pipe(
          catchError(err => {
            return of(err);
          })
        ).subscribe(data => {
          if(data.ok){
            // this.productorder = data.data;
            // console.log(this.productorder);
            // this.reload();
          }else{
            console.log("22")
          }
        })
    }


}
